import OSS from "ali-oss";

export function client() {
    var client = new OSS({
        endpoint: 'oss-cn-hangzhou.aliyuncs.com',
        accessKeyId: 'LTAI5tFV6bi5F7FeVCURA2Mj',
        accessKeySecret: '2UDMPB8uIKO1omwwesq2IDN8v7dwke',
        bucket: 'lu12138',
    })
    return client;
}

export function getFileNameUUID() {
    function rx() {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
    }
    return `${+new Date()}_${rx()}${rx()}`
}

// 新增：上传文件到OSS
export async function uploadFile(file, folder = 'products/') {
    try {
        const clientInstance = client();
        const fileName = folder + getFileNameUUID() + '.' + file.name.split('.').pop();

        const result = await clientInstance.put(fileName, file);
        return {
            success: true,
            url: result.url,
            name: fileName
        };
    } catch (error) {
        console.error('OSS上传失败:', error);
        return {
            success: false,
            error: error.message
        };
    }
}